package org.my.hadoop.test;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class Sort {
       public static class Map extends Mapper<Object, Text, IntWritable, IntWritable>{
    	   private IntWritable data = new IntWritable();
     	   public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
    		   String lineString = value.toString();
    		   data.set(Integer.parseInt(lineString));
    		   context.write(data, new IntWritable(1));
    	   }
       }
       
       public static class Reduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable>{
    	   private static IntWritable line = new IntWritable(1);
    	   public  void reduce(IntWritable key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException{
    		  
    		   for(IntWritable val:values){
    			  context.write(line,key); 
    			  line=new IntWritable(line.get()+1);
    		   }
    	   }
       }
       
       public static class Partition extends Partitioner<IntWritable, IntWritable>{

		@Override
		public int getPartition(IntWritable key, IntWritable value,int numPartitions) {
			int Maxnumber = 65223;
			int bound = Maxnumber/numPartitions+1;
			int keynumber = key.get();
			for(int i=0;i<numPartitions;i++){
				if(keynumber<bound*i && keynumber>=bound*(i-1)){
					return i-1;
				}
			}
			return -1;
		}
    	   
       }
       
       public static void main(String args[]) throws IOException, ClassNotFoundException, InterruptedException{
    	   Configuration conf = new Configuration();
    	   if(args.length<2){
    		   System.err.println("Usage:Sort <in><out>");
    		   System.exit(2);
    	   }
    	   Job job = new Job(conf,"Sort");
    	   job.setJarByClass(Sort.class);
    	   job.setMapperClass(Map.class);
    	   job.setReducerClass(Reduce.class);
    	   job.setPartitionerClass(Partition.class);
    	   job.setOutputKeyClass(IntWritable.class);
    	   job.setOutputValueClass(IntWritable.class);
    	   for(int i=0;i<args.length-1;i++){
    		   FileInputFormat.addInputPath(job, new Path(args[i]));
    	   }
    	   FileOutputFormat.setOutputPath(job, new Path(args[args.length-1]));
    	   System.exit(job.waitForCompletion(true)?0:1);

       }
}
